const { ipcMain, BrowserWindow, app, screen, dialog } = require("electron");
const { selectDictList, selectDictValueList, selectPatient, updatePatient, selectPatientListByName } = require('./dataBase')
const { getData } = require('./storage')
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
//是否是测试环境
const isDevelopment = !app.isPackaged;
//目前存在的window
const windows = {}
let _previewWindow = undefined
module.exports = () => {
    //监听打开新的阅片窗口
    ipcMain.on('REPORT-OPEN-WINDOW', (event, arg) => {
        const { width, height } = screen.getPrimaryDisplay().workAreaSize;
        const { id: p } = arg
        const patientName = decodeURIComponent(p).split('-')[4]
        const id = crypto.createHash('md5').update(p).digest('hex');
        if (windows[id]) {
            windows[id].focus()
            return
        }
        windows[id] = new BrowserWindow({
            titleBarStyle: "hidden",
            fullScreen: true,
            show: false,
            width,
            height,
            title: `报告:${patientName}`,
            icon: path.join(__dirname, '../assets/logo.png'),
            webPreferences: {
                preload: path.join(__dirname, "../preload.js"),
            }
        })
        windows[id].once("ready-to-show", () => {
            windows[id].show();
        });
        if (isDevelopment) {
            windows[id].loadURL(path.join("http://localhost:3321", `p?id=${p}`));
        } else {
            windows[id].loadFile(path.join(__dirname, 'platform/index.html'), {
                hash: `p?id=${p}`,
            });
        }
        windows[id].webContents.openDevTools();
        windows[id].on("close", () => {
            windows[id] = null;
            // eventHandlers[id] = null
        });
    })

    ipcMain.on('DICT-QUERY', async (event, arg) => {
        const { device } = arg
        event.reply('DICT-QUERY-CALL', { rows: await selectDictList(device) })
    })

    ipcMain.on('DICT-VALUE-QUERY', async (event, arg) => {
        const { dictId } = arg
        event.reply('DICT-VALUE-QUERY-CALL', { rows: await selectDictValueList(dictId) })
    })

    ipcMain.on('STUDY-QUERY', async (event, arg) => {
        const { id } = arg
        //注入机构名称
        const hospitalName = await getData('hospitalName')
        event.returnValue = { row: await selectPatient(id), hospitalName }
    })

    ipcMain.on('STUDY-EDIT', async (event, arg) => {
        const { data } = arg
        event.returnValue = { row: await updatePatient(data) }
    })

    ipcMain.on('HISTORY-QUERY', async (event, arg) => {
        const { name } = arg
        event.returnValue = { rows: await selectPatientListByName(name) }
    })

    ipcMain.on('REPORT-PRINT', async (event, arg) => {
        const { id, pn } = arg
        _previewWindow = new BrowserWindow({
            show: false,
            webPreferences: {
                preload: path.join(__dirname, "../preload.js"),
            }
        })
        _previewWindow.loadFile(path.join(__dirname, '../assets/html/report/index.html'), {
            hash: `?id=${id}&pn=${pn}`,
        })
        if (isDevelopment) {
            //是否开启调试
            _previewWindow.webContents.openDevTools();
        }
    })

    ipcMain.on('GET-PRINTERS', async (event, arg) => {
        const window = BrowserWindow.getFocusedWindow()
        const list = await window.webContents.getPrintersAsync();
        event.returnValue = { list }
    })

    ipcMain.on('PLUGIN-PRINT', async (event, arg) => {
        const { printerName } = arg
        if (_previewWindow) {
            _previewWindow.webContents.print({ silent: true, deviceName: printerName }, () => {
                _previewWindow.close()
            })
        }
    })

}